

class Shader {

    constructor(gl, vs, fs, program) {
        this.gl = gl;
        this.vs = vs;
        this.fs = fs;
        this.program = program;

        this.attribs = {};
        this.uniforms = {};

        // this.uniforms = [];
        // this.attributes = [];
        // // parse attribute
        // let numAttributes = gl.getProgramParameter(program,gl.ACTIVE_ATTRIBUTES);
        // for (let i = 0; i < numAttributes; ++i){
        //     let info = gl.getActiveAttrib(program,i);
        //     let location = gl.getAttribLocation(program,info.name);
        //     this.attributes.push({
        //         name:info.name,
        //         location:location,
        //         type:info.type
        //     });
        // }
        //
        // // parse uniform
        // let numUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
        // for (let i = 0; i < numUniforms; ++i) {
        //     let info = gl.getActiveUniform(program, i);
        //     let name = info.name;
        //     let location = gl.getUniformLocation(program, name);
        //     let isArray = name.substr(name.length - 3) === '[0]';
        //     if (isArray) {
        //         name = name.substr(0, name.length - 3);
        //     }
        //     console.log('name:',name);
        //     let uniform = {
        //         name: name,
        //         location: location,
        //         type: info.type,
        //         size: isArray ? info.size : undefined, // used when uniform is an array
        //     };
        //     this.uniforms.push(uniform);
        // }
    }

    createUniforms(uniformNames) {
        let gl = this.gl;
        uniformNames.forEach(name => {
            let location = gl.getUniformLocation(this.program, name);
            if (!location) {
                throw `getUniformLocation for ${name} failed!`;
            }
            this.uniforms[name] = location;
        });
    }

    createAttribs(attribs) {
        let gl = this.gl;
        attribs.forEach(name => {
            let location = gl.getAttribLocation(this.program, name);
            if (location < 0) {
                throw `getAttribLocation for ${name} failed!`;
            }
            this.attribs[name] = location;
        });
    }


    /**
     *
     * @param name
     * @param matrix4 {Matrix4}
     */
    setMatrix4(name,matrix4){
        this.gl.uniformMatrix4fv(this.uniforms[name],false,matrix4.elements);
    }

    setUniform1i(name,num){
        this.gl.uniform1i(this.uniforms[name],num);
    }

}

module.exports = Shader;
